import configparser
import os

from PyQt5.QtWidgets import QWidget, QPushButton, QListWidget, QFileDialog


class File(QWidget):
    """管理歌曲列表，加载音乐文件的类"""
    def __init__(self,MP3Player):
        super().__init__()
        #基本控件
        self.openBtn = QPushButton(self)
        self.musicList = QListWidget()
        self.song_formats = ['mp3', 'm4a', 'flac', 'wav', 'ogg']
        self.songs_list = []  # 列表套列表，里面每个列表包括歌曲名和其完整路径
        self.cur_playing_song = ''  # 当前歌曲路径
        self.settingfilename = 'config.ini'
        self.is_pause = True
        #取自MP3Player中的控件
        self.ms = MP3Player.ms
        self.startTimeLabel = self.ms.startTimeLabel
        self.endTimeLabel = self.ms.endTimeLabel
        self.slider = self.ms.slider
        self.playBtn = MP3Player.playBtn
        #初始化
        self.openBtn.setStyleSheet("QPushButton{border-image: url(:/resource/images/open-file.png)}")
        self.openBtn.setFixedSize(32, 32)
        #SignalSlot
        self.openBtn.clicked.connect(self.openMusicFloder)


    def openMusicFloder(self):
        """打开文件夹"""
        self.cur_path = QFileDialog.getExistingDirectory(self, "选取音乐文件夹", './')
        if self.cur_path:
            self.showMusicList()
            self.cur_playing_song = ''
            self.startTimeLabel.setText('00:00')
            self.endTimeLabel.setText('00:00')
            self.slider.setSliderPosition(0)
            self.updateSetting()
            self.is_pause = True
            self.playBtn.setStyleSheet("QPushButton{border-image: url(:/resource/images/play.png)}")

    def showMusicList(self):
        """显示音乐列表"""
        self.musicList.clear()
        for song in os.listdir(self.cur_path):
            if song.split('.')[-1] in self.song_formats:
                self.songs_list.append([song, os.path.join(self.cur_path, song).replace('\\', '/')])
                # song = "❤" + song
                self.musicList.addItem(song)
        self.musicList.setCurrentRow(0)
        if self.songs_list:
            self.cur_playing_song = self.songs_list[self.musicList.currentRow()][-1]

    def updateSetting(self):
        """更新配置文件"""
        config = configparser.ConfigParser()    #主要使用ConfigParser类来解析ini文件
        config.read(self.settingfilename)
        if not os.path.isfile(self.settingfilename):
            config.add_section('MP3Player')    #如果section不存在，则添加节点section；若section已存在，再执行add操作会报错
        config.set('MP3Player', 'PATH', self.cur_path)
        config.write(open(self.settingfilename, 'w'))    #对configparser对象执行的一些修改操作，必须重新写回到文件才可生效

    def loadingSetting(self):
        """加载配置文件"""
        config = configparser.ConfigParser()
        config.read(self.settingfilename)
        if not os.path.isfile(self.settingfilename):
            return
        self.cur_path = config.get('MP3Player', 'PATH')
        self.showMusicList()